<template>
  <view class="detail-container">
    <!-- 地址卡片 -->
    <view class="address-detail">
      <view class="address-info">
        <uni-icons type="location" size="16"></uni-icons>
        <view class="address-item">
          <view class="address-buyer">
            <text>{{ orderDetail.buyer_name }}</text>
            <text>{{ orderDetail.buyer_mobile }}</text>
          </view>
          <view class="address-name">
            {{  orderDetail.detail_address }}
          </view>
        </view>
      </view>
    </view>

    <!-- 订单详情卡片 -->
    <view class="layout-padding">
      <view class="order-detail">
        <view class="order-title">订单信息</view>
        <view class="order-info">
          <!-- 订单摘要信息 -->
          <view class="order-summary">
            <text class="label">订单编号</text>
            <text class="value">{{ orderDetail.order_sn }}</text>
          </view>
          <view class="order-summary">
            <text class="label">下单时间</text>
            <text class="value">{{ orderDetail.created_at }}</text>
          </view>
          <view class="order-summary">
            <text class="label">配送方式</text>
            <text class="value">{{ orderDetail.delivery_method }}</text>
          </view>
          <view class="order-summary">
            <text class="label">订单状态</text>
            <text class="value" :class="getStatusClass(orderDetail.order_status)">
              {{ orderDetail.order_status_text }}
            </text>
          </view>
        </view>
      </view>

      <!-- 商品信息列表 -->
      <view class="product-list">
        <view class="section-title">商品信息</view>
        <view class="product-item" v-for="(product, index) in orderDetail.products" :key="index">
          <image 
            :src="product.image" 
            class="product-image" 
            mode="aspectFill"
            @error="handleImageError"
          />
          <view class="product-info">
            <view class="product-name">{{ product.name }}</view>
            <view class="product-spec">{{ product.spec }}</view>
          </view>
          <view class="product-quantity">×{{ product.num }}</view>
        </view>
        <view class="order-total">
          <text>共{{ orderDetail.products?.length || 0 }}件商品</text>
        </view>
      </view>

      <!-- 物流信息 -->
      <view class="logistics-info" v-if="showLogistics">
        <view class="section-title">物流信息</view>
        <view class="logistics-header">
          <text>物流公司: {{ orderDetail.logistics?.company || '暂无' }}</text>
          <text>运单号: {{ orderDetail.logistics?.tracking_number || '暂无' }}</text>
        </view>
        <view class="logistics-status">
          <text>物流状态: {{ orderDetail.logistics?.status || '暂无物流信息' }}</text>
          <text class="copy-btn" @click="copyTrackingNumber">复制运单号</text>
        </view>
        <view class="logistics-timeline" v-if="orderDetail.logistics?.traces?.length">
          <view 
            class="timeline-item" 
            v-for="(trace, index) in orderDetail.logistics.traces" 
            :key="index"
            :class="{ 'first-item': index === 0 }"
          >
            <view class="timeline-dot"></view>
            <view class="timeline-content">
              <view class="timeline-time">{{ trace.time }}</view>
              <view class="timeline-desc">{{ trace.desc }}</view>
            </view>
          </view>
        </view>
        <view v-else class="no-logistics">
          <text>暂无物流跟踪信息</text>
        </view>
      </view>

      <!-- 底部操作按钮 -->
      <view class="action-buttons">
        <button 
          v-if="showCancelButton(orderDetail.order_status)" 
          class="action-button cancel" 
          @click="handleCancelOrder"
        >
          取消订单
        </button>
        <button 
          class="action-button home" 
          @click="backHome"
        >
          返回首页
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from "vue";
import uniIcons from "@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue";
import { onLoad } from "@dcloudio/uni-app";
import { showToast, showModal, showError } from "@/utils/feedback";
import { orderDetailApi } from "@/api/order";

// 订单状态常量
const ORDER_STATUS = {
  PENDING_PAYMENT: '0',
  PENDING_SHIPMENT: '1',
  SHIPPED: '2',
  PENDING_RECEIPT: '3',
  COMPLETED: '4',
  CANCELLED: '-4'
};

// 响应式数据
const order_id = ref(null);
const orderDetail = ref({
  id: null,
  order_sn: '',
  created_at: '',
  delivery_method: '',
  buyer_name: '',
  buyer_mobile: '',
  province_name: '',
  city_name: '',
  district_name: '',
  detail_address: '',
  order_status: '',
  order_status_text: '',
  payment_method: '',
  products: [],
  logistics: null
});

/**
 * 页面加载时获取订单ID
 */
onLoad((options) => {
  if (!options.id) {
    showToast('订单ID缺失');
    uni.switchTab({ url: '/pages/index/index' });
    return;
  }
  order_id.value = options.id;
  fetchOrderDetail();
});

/**
 * 获取订单详情
 */
const fetchOrderDetail = async () => {
  try {
    const res = await orderDetailApi({ id: order_id.value });
    if (res.code == 200) {
      orderDetail.value = res.data;
      // 模拟物流数据 - 实际项目中应从API获取
      if (['2', '3', '4'].includes(res.data.order_status)) {
        orderDetail.value.logistics = {
          company: '顺丰速运',
          tracking_number: 'SF1234567890',
          status: '运输中',
          traces: [
            {
              time: '2024-01-05 14:30:00',
              desc: '快件已到达【北京转运中心】'
            },
            {
              time: '2024-01-05 10:15:00',
              desc: '快件已从【北京朝阳集散点】发出'
            },
            {
              time: '2024-01-04 18:20:00',
              desc: '商家已发货'
            }
          ]
        };
      }
    } else {
      showError(res.message || '获取订单详情失败');
      uni.navigateBack();
    }
  } catch (error) {
    console.error('获取订单详情失败:', error);
    showError('网络错误，请稍后重试');
    uni.navigateBack();
  }
};

/**
 * 是否显示物流信息
 */
const showLogistics = computed(() => {
  return ['2', '3', '4'].includes(orderDetail.value.order_status);
});


/**
 * 处理图片加载失败
 */
const handleImageError = (e) => {
  e.target.src = '/static/images/default-product.png';
};


/**
 * 复制运单号
 */
const copyTrackingNumber = () => {
  if (!orderDetail.value.logistics?.tracking_number) {
    showToast('暂无快递单号');
    return;
  }
  uni.setClipboardData({
    data: orderDetail.value.logistics.tracking_number,
    success: () => showToast('快递单号已复制')
  });
};

/**
 * 获取订单状态对应的CSS类
 */
const getStatusClass = (status) => ({
  'pending-payment': status == ORDER_STATUS.PENDING_PAYMENT,
  'pending-shipment': status == ORDER_STATUS.PENDING_SHIPMENT,
  'shipped': status == ORDER_STATUS.SHIPPED,
  'pending-receipt': status == ORDER_STATUS.PENDING_RECEIPT,
  'completed': status == ORDER_STATUS.COMPLETED,
  'cancelled': status == ORDER_STATUS.CANCELLED
});

/**
 * 是否显示取消按钮
 */
const showCancelButton = (status) => {
  return [ORDER_STATUS.PENDING_PAYMENT, ORDER_STATUS.PENDING_SHIPMENT].includes(status);
};

/**
 * 处理取消订单
 */
const handleCancelOrder = async () => {
  const confirmed = await showModal('确认', '确定要取消该订单吗？');
  if (confirmed) {
    try {
      // TODO: 调用取消订单API
      showToast('订单已取消');
      fetchOrderDetail(); // 刷新订单状态
    } catch (error) {
      console.error('取消订单失败:', error);
      showToast('取消订单失败');
    }
  }
};

/**
 * 处理联系客服
 */
const handleContact = () => {
  uni.makePhoneCall({
    phoneNumber: '400-123-4567'
  });
};

/**
 * 返回首页
 */
const backHome = () => {
  uni.switchTab({ url: '/pages/index/index' });
};
</script>

<style scoped lang="scss">

.detail-container {
  display: flex;
  flex-direction: column;
}

.layout-padding {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
  flex: 1;
}

// 公共样式
.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #409eff;
  padding-bottom: 10px;
  margin-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

// 地址卡片样式
.address-detail {
  background-color: #ffffff;
  padding: 16px;
  margin-bottom: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  .address-info {
    display: flex;
    align-items: center;
    gap: 10px;

    .address-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 6px;

      .address-buyer {
        display: flex;
        gap: 12px;
        font-size: 16px;
        color: #333;
      }

      .address-name {
        font-size: 14px;
        color: #666;
        line-height: 1.5;
      }
    }
  }
}

// 订单详情卡片样式
.order-detail {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  .order-title {
    font-size: 16px;
    color: #409eff;
    font-weight: bold;
    margin-bottom: 10px;
    border-bottom: 1px solid #f0f0f0;
    padding-bottom: 10px;
  }

  .order-info {
    display: flex;
    flex-direction: column;
    gap: 12px;

    .order-summary {
      display: flex;
      justify-content: space-between;
      font-size: 14px;
      line-height: 1.5;

      .label {
        color: #666;
      }

      .value {
        color: #333;
        text-align: right;
        
        &.pending-payment {
          color: #f97316;
        }
        &.pending-shipment {
          color: #f97316;
        }
        &.shipped {
          color: #3b82f6;
        }
        &.pending-receipt {
          color: #cc42e8;
        }
        &.completed {
          color: #10b981;
        }
        &.cancelled {
          color: #ef4444;
        }
      }
    }
  }
}

// 商品列表样式
.product-list {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  .product-item {
    display: flex;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px dashed #f0f0f0;

    .product-image {
      width: 60px;
      height: 60px;
      border-radius: 4px;
      background-color: #f5f5f5;
      margin-right: 12px;
    }

    .product-info {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 4px;

      .product-name {
        font-size: 14px;
        color: #333;
      }

      .product-spec {
        font-size: 12px;
        color: #999;
      }

      .product-price {
        font-size: 14px;
        color: #f56c6c;
      }
    }

    .product-quantity {
      width: 40px;
      text-align: center;
      font-size: 14px;
      color: #666;
    }

    .product-total {
      width: 80px;
      text-align: right;
      font-size: 14px;
      color: #333;
      font-weight: bold;
    }
  }

  .order-total {
    display: flex;
    justify-content: flex-end;
    padding-top: 10px;
    font-size: 14px;
    color: #333;
    font-weight: bold;
  }
}

// 物流信息样式
.logistics-info {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  .logistics-header {
    display: flex;
    flex-direction: column;
    gap: 8px;
    font-size: 14px;
    color: #333;
    margin-bottom: 12px;
  }

  .logistics-status {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 14px;
    color: #333;
    margin-bottom: 16px;

    .copy-btn {
      color: #f37b1d;
      font-size: 12px;
      padding: 4px 8px;
      border: 1px solid #f37b1d;
      border-radius: 12px;
    }
  }

  .logistics-timeline {
    position: relative;
    padding-left: 20px;

    .timeline-item {
      position: relative;
      padding-bottom: 16px;

      &.first-item {
        .timeline-dot {
          background-color: #f37b1d;
        }
        
        .timeline-time {
          color: #f37b1d;
          font-weight: bold;
        }
      }

      .timeline-dot {
        position: absolute;
        left: -20px;
        top: 4px;
        width: 10px;
        height: 10px;
        border-radius: 50%;
        background-color: #ccc;
        z-index: 2;
      }

      .timeline-content {
        font-size: 13px;
        
        .timeline-time {
          color: #666;
          margin-bottom: 4px;
        }
        
        .timeline-desc {
          color: #333;
        }
      }

      &:not(:last-child)::after {
        content: '';
        position: absolute;
        left: -16px;
        top: 14px;
        bottom: 0;
        width: 2px;
        background-color: #e0e0e0;
      }
    }
  }

  .no-logistics {
    text-align: center;
    padding: 20px 0;
    color: #999;
  }
}

// 操作按钮样式
.action-buttons {
  display: flex;
  gap: 10px;
  margin-top: 20px;

  .action-button {
    flex: 1;
    margin: 0;
    padding: 8px 0;
    font-size: 14px;
    border-radius: 10px;
    border: 1px solid #ddd;
    background-color: transparent;

    &.cancel {
      color: #666;
    }

    &.contact {
      color: #f37b1d;
      border-color: #f37b1d;
    }

    &.home {
      color: #fff;
      background-color: #409eff;
      border-color: #409eff;
    }
  }
}
</style>